# 简化版图床系统 - 不依赖Flask-Login
from flask import Flask, request, jsonify, render_template, send_from_directory, redirect, url_for, flash, session
from werkzeug.utils import secure_filename
from werkzeug.security import check_password_hash, generate_password_hash
from PIL import Image
import os
import uuid
import json
from datetime import datetime
import shutil
from functools import wraps

app = Flask(__name__)
app.config['SECRET_KEY'] = 'your-secret-key-here-change-in-production'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024  # 16MB max file size

# 确保上传目录存在
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
os.makedirs('thumbnails', exist_ok=True)

# 支持的图片格式
ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp'}

# 用户数据（实际项目中应使用数据库）
users_db = {
    'admin': {
        'password': generate_password_hash('admin123'),
        'role': 'admin'
    },
    'user': {
        'password': generate_password_hash('user123'),
        'role': 'user'
    }
}

# 图片数据库（JSON文件）
IMAGES_DB = 'images_db.json'

def login_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            return redirect(url_for('login'))
        return f(*args, **kwargs)
    return decorated_function

def admin_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if 'user_id' not in session:
            return redirect(url_for('login'))
        user = users_db.get(session['user_id'])
        if not user or user['role'] != 'admin':
            return jsonify({'error': '权限不足'}), 403
        return f(*args, **kwargs)
    return decorated_function

def get_current_user():
    if 'user_id' in session:
        user_id = session['user_id']
        if user_id in users_db:
            return {
                'username': user_id,
                'role': users_db[user_id]['role'],
                'is_authenticated': True
            }
    return {'is_authenticated': False}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

def load_images_db():
    """加载图片数据库"""
    if os.path.exists(IMAGES_DB):
        try:
            with open(IMAGES_DB, 'r', encoding='utf-8') as f:
                return json.load(f)
        except:
            return {}
    return {}

def save_images_db(data):
    """保存图片数据库"""
    with open(IMAGES_DB, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def create_thumbnail(image_path, thumbnail_path, size=(200, 200)):
    """创建缩略图 - 优化版本"""
    try:
        with Image.open(image_path) as img:
            # 如果是RGBA模式，转换为RGB
            if img.mode == 'RGBA':
                img = img.convert('RGB')
            
            # 快速缩略图算法
            img.thumbnail(size, Image.Resampling.NEAREST)  # 使用最快的算法
            
            # 优化保存参数
            img.save(thumbnail_path, 'JPEG', optimize=True, quality=75)
        return True
    except Exception as e:
        print(f"Error creating thumbnail: {e}")
        return False

@app.context_processor
def inject_user():
    return dict(current_user=get_current_user())

@app.route('/')
def index():
    return render_template('index_lite.html')

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        
        if username in users_db and check_password_hash(users_db[username]['password'], password):
            session['user_id'] = username
            
            if users_db[username]['role'] == 'admin':
                return redirect(url_for('admin_dashboard'))
            else:
                return redirect(url_for('user_gallery'))
        else:
            flash('用户名或密码错误')
    
    return render_template('login_lite.html')

@app.route('/logout')
@login_required
def logout():
    session.pop('user_id', None)
    return redirect(url_for('index'))

@app.route('/admin')
@login_required
def admin_dashboard():
    user = get_current_user()
    if user['role'] != 'admin':
        return redirect(url_for('user_gallery'))
    
    # 获取统计信息
    stats = get_image_stats()
    
    # 获取所有图片信息，转换为列表格式
    images_db = load_images_db()
    images = []
    for filename, data in images_db.items():
        images.append({
            'filename': data.get('filename', filename),
            'thumbnail': data.get('thumbnail', f'thumb_{data.get("filename", filename)}'),
            'width': data.get('width', 0),
            'height': data.get('height', 0),
            'size': data.get('size', 0),
            'upload_time': datetime.fromisoformat(data.get('upload_time', datetime.now().isoformat()))
        })
    
    # 按上传时间排序（最新的在前）
    images.sort(key=lambda x: x['upload_time'], reverse=True)
    
    return render_template('admin_lite.html', stats=stats, images=images)

@app.route('/gallery')
@login_required
def user_gallery():
    # 获取所有图片信息，转换为列表格式
    images_db = load_images_db()
    images = []
    for filename, data in images_db.items():
        images.append({
            'filename': data.get('filename', filename),
            'thumbnail': data.get('thumbnail', f'thumb_{data.get("filename", filename)}'),
            'width': data.get('width', 0),
            'height': data.get('height', 0),
            'size': data.get('size', 0),
            'upload_time': datetime.fromisoformat(data.get('upload_time', datetime.now().isoformat()))
        })
    
    # 按上传时间排序（最新的在前）
    images.sort(key=lambda x: x['upload_time'], reverse=True)
    
    return render_template('gallery_lite.html', images=images)

@app.route('/api/upload', methods=['POST'])
@admin_required
def upload_image():
    if 'file' not in request.files:
        return jsonify({'success': False, 'message': '没有文件'}), 400
    
    files = request.files.getlist('file')
    if not files or all(f.filename == '' for f in files):
        return jsonify({'success': False, 'message': '没有选择文件'}), 400
    
    uploaded_files = []
    errors = []
    
    for file in files:
        if file and file.filename and allowed_file(file.filename):
            try:
                # 生成唯一文件名
                file_extension = file.filename.rsplit('.', 1)[1].lower()
                unique_filename = f"{uuid.uuid4().hex}.{file_extension}"
                
                # 保存原图
                file_path = os.path.join(app.config['UPLOAD_FOLDER'], unique_filename)
                file.save(file_path)
                
                # 创建缩略图
                thumbnail_filename = f"thumb_{unique_filename}"
                thumbnail_path = os.path.join('thumbnails', thumbnail_filename)
                if not create_thumbnail(file_path, thumbnail_path):
                    # 如果缩略图创建失败，使用原图
                    shutil.copy(file_path, thumbnail_path)
                
                # 获取图片信息
                try:
                    with Image.open(file_path) as img:
                        width, height = img.size
                except:
                    width, height = 0, 0
                
                file_size = os.path.getsize(file_path)
                
                # 保存到数据库
                images_db = load_images_db()
                image_id = unique_filename.split('.')[0]
                
                images_db[image_id] = {
                    'id': image_id,
                    'filename': unique_filename,
                    'original_name': file.filename,
                    'upload_time': datetime.now().isoformat(),
                    'uploader': session['user_id'],
                    'width': width,
                    'height': height,
                    'size': file_size,
                    'thumbnail': thumbnail_filename
                }
                
                save_images_db(images_db)
                uploaded_files.append(unique_filename)
                
            except Exception as e:
                errors.append(f'{file.filename}: {str(e)}')
        else:
            errors.append(f'{file.filename}: 不支持的文件格式')
    
    if uploaded_files:
        message = f'成功上传 {len(uploaded_files)} 个文件'
        if errors:
            message += f'，{len(errors)} 个文件失败'
        return jsonify({
            'success': True,
            'uploaded_files': uploaded_files,
            'errors': errors,
            'message': message
        })
    else:
        return jsonify({
            'success': False, 
            'message': f'上传失败：{"; ".join(errors)}' if errors else '上传失败'
        }), 400

@app.route('/api/images')
@login_required
def get_images():
    images_db = load_images_db()
    images_list = list(images_db.values())
    
    # 按上传时间排序
    images_list.sort(key=lambda x: x['upload_time'], reverse=True)
    
    return jsonify(images_list)

@app.route('/api/delete', methods=['POST'])
@admin_required
def delete_image_api():
    data = request.get_json()
    if not data or 'filename' not in data:
        return jsonify({'success': False, 'message': '缺少文件名'}), 400
    
    filename = data['filename']
    images_db = load_images_db()
    
    # 查找对应的图片记录
    image_id = None
    for id, info in images_db.items():
        if info.get('filename') == filename:
            image_id = id
            break
    
    if not image_id:
        return jsonify({'success': False, 'message': '图片不存在'}), 404
    
    image_info = images_db[image_id]
    
    # 删除原图
    image_path = os.path.join(app.config['UPLOAD_FOLDER'], image_info['filename'])
    if os.path.exists(image_path):
        os.remove(image_path)
    
    # 删除缩略图
    thumbnail_path = os.path.join('thumbnails', image_info['thumbnail'])
    if os.path.exists(thumbnail_path):
        os.remove(thumbnail_path)
    
    # 从数据库删除
    del images_db[image_id]
    save_images_db(images_db)
    
    return jsonify({'success': True, 'message': '删除成功'})

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)

@app.route('/thumbnails/<filename>')
def thumbnail_file(filename):
    return send_from_directory('thumbnails', filename)

def get_image_stats():
    """获取图片统计信息 - 内部使用"""
    images_db = load_images_db()
    
    total_images = len(images_db)
    total_size = sum(img.get('size', 0) for img in images_db.values())
    
    # 计算今日上传数量
    today = datetime.now().date()
    uploaded_today = 0
    for img in images_db.values():
        try:
            upload_date = datetime.fromisoformat(img.get('upload_time', '')).date()
            if upload_date == today:
                uploaded_today += 1
        except:
            continue
    
    # 计算平均文件大小
    avg_file_size_mb = round((total_size / total_images / (1024 * 1024)), 1) if total_images > 0 else 0
    
    return {
        'total_images': total_images,
        'total_size': total_size,
        'uploaded_today': uploaded_today,
        'total_size_mb': round(total_size / (1024 * 1024), 1),
        'avg_file_size_mb': avg_file_size_mb
    }

@app.route('/api/stats')
@admin_required
def get_stats():
    """API端点 - 获取统计信息"""
    return jsonify(get_image_stats())

if __name__ == '__main__':
    print("=" * 50)
    print("图床系统启动成功！")
    print("访问地址: http://localhost:5001")
    print("管理员账号: admin / admin123")
    print("用户账号: user / user123")
    print("=" * 50)
    app.run(debug=True, host='0.0.0.0', port=8001)
